package com.zzjson.redis;

import com.zzjson.common.utils.PropertiesUtils;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;

import java.util.HashSet;
import java.util.Properties;
import java.util.Set;

/**
 * <p>****************************************************************************</p>
 * <li>Description : TODO </li>
 * <li>Version     : 1.0.0</li>
 * <li>Creation    : 2021年03月02日</li>
 * <li>@author     : zzy0_0</li>
 * </ul>
 * <p>****************************************************************************</p>
 */
public class JedisClustExample {
	public static Properties properties = PropertiesUtils.loadProperties("redis-cluster");

	public static void main(String[] args) {

		JedisPoolConfig config = new JedisPoolConfig();
		config.setMaxTotal(20);
		config.setMaxIdle(10);
		config.setMinIdle(5);

		Set<HostAndPort> jedisClusterNode = getHostAndPorts();

		try (JedisCluster jedisCluster = new JedisCluster(jedisClusterNode, 6000, 5000, 10, "mypassword", config)) {
			//connectionTimeout：指的是连接一个url的连接等待时间
			//soTimeout：指的是连接上一个url，获取response的返回等待时间
			System.out.println(jedisCluster.set("cluster", "zzjson"));
			System.out.println(jedisCluster.get("cluster"));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static Set<HostAndPort> getHostAndPorts() {
		Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
		String masterString = "cluster%s.master";
		String slaveString = "cluster%s.slave";
		for (int i = 1; i <= 3; i++) {
			String master = String.format(masterString, i);
			String slave = String.format(slaveString, i);
			HostAndPort masterHostAndPort = new HostAndPort(properties.getProperty(master + ".host"), Integer.parseInt(properties.getProperty(master + ".port")));
			HostAndPort slaveHostAndPort = new HostAndPort(properties.getProperty(slave + ".host"), Integer.parseInt(properties.getProperty(slave + ".port")));
			jedisClusterNode.add(masterHostAndPort);
			jedisClusterNode.add(slaveHostAndPort);
		}
		return jedisClusterNode;
	}
}